<template><!--编辑-->
    <div style="height:100%;">
        <navbar :title="`${$t('knowledge_edit')}${shareType}`" :backCallback="back">
            <template #right>
                <span class="font-size15 write-btn-right" v-if="(($route.query.type != 'ARTICLE' && (kbi_title == '' || upFiles.length == 0)) || ($route.query.type == 'ARTICLE' && (kbi_title == '' || content == '' || errors.has('tipsContent')))) || catalogSelected.length == 0 || errors.has('tipsTitle') || errors.has('tipsDetail')">{{ $t("knowledge_share_add") }}</span><!--分享-->
                <span class="font-size15 write-btn-right cur" @click="save" v-if="(($route.query.type != 'ARTICLE' && kbi_title != '' && upFiles.length != 0) || ($route.query.type == 'ARTICLE' && kbi_title != '' && content != '' && !errors.has('tipsContent'))) && catalogSelected.length != 0 && !errors.has('tipsTitle') && !errors.has('tipsDetail')">{{ $t("knowledge_share_add") }}</span>
            </template>
        </navbar>
        <div class="content-noBottom">
            <div class="layer-content-box">
                <div class="add-contents-box">
                    <p class="word-title-06">{{ $t("knowledge_share_title") }}</p><!--标题(必填)-->
                    <div class="white-bg bottom-shadow">
                        <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_1')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'ARTICLE'"></textarea>
                        <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_2')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'DOCUMENT'"></textarea>
                        <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_3')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'IMAGE'"></textarea>
                        <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_4')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'VEDIO'"></textarea>
                        <textarea v-validate="'tipsTitle'" name="tipsTitle" v-model="kbi_title" :placeholder="$t('knowledge_share_title_tips_5')" style="height: 41px;font-size: 16px;" v-if="$route.query.type == 'FILES'"></textarea><!--输入文件标题...-->
                        <p  class="font-size11 colorfd3 warning-red-tan warning" v-if="errors.has('tipsTitle')">{{ $t("exceeded_word_range_tips", {'value': '40'}) }}</p><!--40-->
                    </div>
                    <p class="word-title-06">{{ $t("mod_desc") }}</p><!--简介-->
                    <div class="white-bg">
                        <textarea v-validate="'tipsDetail'" name="tipsDetail" v-model="kbi_desc" :placeholder="$t('knowledge_share_desc_tips_1')" style="height: 60px;" v-if="$route.query.type == 'ARTICLE'"></textarea>
                        <textarea v-validate="'tipsDetail'" name="tipsDetail" v-model="kbi_desc" :placeholder="$t('knowledge_share_desc_tips_2')" style="height: 60px;" v-if="$route.query.type == 'DOCUMENT'"></textarea>
                        <textarea v-validate="'tipsDetail'" name="tipsDetail" v-model="kbi_desc" :placeholder="$t('knowledge_share_desc_tips_3')" style="height: 60px;" v-if="$route.query.type == 'IMAGE'"></textarea>
                        <textarea v-validate="'tipsDetail'" name="tipsDetail" v-model="kbi_desc" :placeholder="$t('knowledge_share_desc_tips_4')" style="height: 60px;" v-if="$route.query.type == 'VEDIO'"></textarea>
                        <textarea v-validate="'tipsDetail'" name="tipsDetail" v-model="kbi_desc" :placeholder="$t('knowledge_share_desc_tips_2')" style="height: 60px;" v-if="$route.query.type == 'FILES'"></textarea>
                        <p class="font-size11 colorfd3 warning-red-tan warning" v-if="errors.has('tipsDetail')">{{ $t("exceeded_word_range_tips", {'value': '200'}) }}</p><!--200-->
                    </div>
                    <!--文章内容-->
                    <div v-if="$route.query.type === 'ARTICLE'">
                        <p class="word-title-06">{{ $t("knowledge_share_content") }}</p><!--内容(必填)-->
                        <div class="white-bg">
                            <textarea v-validate="'tipsContent'" name="tipsContent" v-model="content" :placeholder="$t('knowledge_share_content_tips_art')"></textarea>
                            <p class="font-size11 colorfd3 warning-red-tan warning" v-if="errors.has('tipsContent')">{{ $t("exceeded_word_range_tips", {'value': '10000'}) }}</p><!--10000-->
                        </div>
                    </div>
                    <!--添加图片-->
                    <div class="border-top2 bottom-shadow white-bg module-box-18 clearfix" v-if="$route.query.type == 'IMAGE'">
                        <div class="module-img-box" style="margin-top: 20px;" v-if="upFiles.length == 0">
                            <div class="box-table" style="height: 70px;">
                                <div class="box-table-cell">
                                    <p class="color999 font-size13">{{ $t("lab_file_tips_8") }}</p><!--注：支持jpg、jpeg、gif、png格式的文件-->
                                </div>
                            </div>
                        </div>
                        <label class="add-icon-box-02" style="float: right; margin-right: -85px;">
                            <input type="file" @change="shareUpFile" hidden>
                            <span class="add-icon-02"></span>
                        </label>
                        <!--添加图片后-->
                        <div class="module-img-box">
                            <div class="img-box-2" v-for="(item, index) in upFiles" :key="index">
                                <img :src="appUrl + item.kba_url" alt="" style="width: 100%;height: 100%;" />
                                <em @click="deleteUpFile(index, item.kba_id)" class="img-delete"></em>
                            </div>
                        </div>
                    </div>
                    <div class="border-top2 bottom-shadow white-bg module-box-18 clearfix" :style="{'padding-right' :upFiles.length !== 0 ? '15px' : '100px'}" v-if="$route.query.type !== 'ARTICLE' && $route.query.type !== 'IMAGE'">
                        <!--添加文档、视频的提示-->
                        <div v-if="upFiles.length == 0">
                            <div class="module-img-box" style="margin-top: 20px;">
                                <div class="box-table" style="height: 70px;">
                                    <p class="color999 box-table-cell" v-if="$route.query.type == 'DOCUMENT'">{{ $t("lab_file_tips_9") }}</p><!--注：支持doc、docx、xls、xlsx、ppt、pdf格式的文件-->
                                    <p class="color999 box-table-cell" v-if="$route.query.type == 'VEDIO'">{{ $t("lab_file_tips_10") }}</p><!--注：支持MP4格式的文件-->
                                    <p class="color999 box-table-cell" v-if="$route.query.type == 'FILES'">{{ $t("lab_file_tips_15") }}</p><!--注：支持doc、docx、xls、xlsx、ppt、pdf、txt、mp4、avi、flv、mov、3gp和mp3格式-->
                                </div>
                            </div>
                            <label class="add-icon-box-02" style="float: right; margin-right: -85px;">
                                <input type="file" @change="shareUpFile" hidden>
                                <span class="add-icon-02"></span>
                            </label>
                        </div>
                        <!--文件上传后-->
                        <ul class="upload-doc">
                            <li v-for="(item, index) in upFiles" :key="index">
                                <div  class="other-upFile-style">
                                    <div style="margin-right: 5px;">
                                        <i class="link-document"></i>
                                    </div>
                                    <div>
                                        <span>{{ item.kba_filename | omit( item.kba_file.split('.')[1] ) }}</span>
                                    </div>
                                    <i class="icon-delete-file" @click="deleteUpFile(index, item.kba_id)"></i>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="margin-top10">
                    <ul class="module-list-10">
                        <li class="clearfix" @click="tagSelect('classify')">
                            <span class="font-size15">{{ $t("knowledge_share_cat") }}</span><!--分类(必选)-->
                            <i class="arrow-right"></i>
                            <span class="color999 word-title-08">
                                <em v-for="(item, index) in classificationList" :key="index">{{item.kbc_title}}<i v-if="classificationList.length -1 != index">,</i></em>
                            </span>
                        </li>
                        <li class="clearfix" @click="tagSelect('tag')">
                            <span class="font-size15">{{ $t("knowledge_lab") }}</span><!--标签-->
                            <i class="arrow-right"></i>
                            <span class="color999 word-title-08">
                                <em v-for="(item, index) in labelList" :key="index">{{item.tag_title}}<i v-if="labelList.length -1 != index">,</i></em>
                            </span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="popup-box" v-if="tagToggle">
            <div v-if="toggleType === 'classify'">
                <div class="layer-header-box white-bg">
                    <span class="icon-back-layer" @click="closeLayer('catalogSelected')"></span>
                    {{ $t("knowledge_cat") }}
                    <span class="font-size15 write-btn-right" :class="{'cur' : catalogSelected.length != 0}" @click="classificationSave" v-if="catalogSelected.length != 0">{{ $t("save") }}</span><!--保存-->
                    <span class="font-size15 write-btn-right" v-if="catalogSelected.length == 0">{{ $t("save") }}</span>
                </div>
                <div class="headerSelect-alert5" style="padding: 20px 0;height: calc(100% - 96px);">
                    <p class="color999 paddingLR15">{{ $t("knowledge_share_classify") }}</p><!--可选择一个或多个分类-->
                    <ul>
                        <li v-for="(klClassify, index) in getClassifyList" :key="klClassify.kbc_id" style="padding: 0;">
                            <input hidden class="catalog"
                                    type="checkbox"
                                    :id="`catalog${index}`"
                                    :value="klClassify"
                                    :checked="checkedCatalogCompute(klClassify.kbc_id)"
                                    @click="selectedCatalogHandle(klClassify)"
                                    >
                            <label :for="`catalog${index}`" style="padding: 0 10px;display: block;border-radius: 4px;">
                                {{ klClassify.kbc_title }}
                            </label>
                        </li>
                    </ul>
                </div>
                <!--暂无数据-->
                <div class="box-table" style="width:100%;height:500px;" v-if="getClassifyList.length === 0">
                    <div class="box-table-cell" style="text-align: center;">
                        <div class="no-data">
                            <img src="../../../static/images/no-data.png" alt=""/>
                            <p class="color999">{{ $t('no_data') }}</p>
                        </div>
                    </div>
                </div>
            </div>
            <div v-if="toggleType === 'tag'">
                <div class="layer-header-box white-bg">
                    <span class="icon-back-layer" @click="closeLayer('tagsSelected')"></span>
                    {{ $t("knowledge_lab") }}
                    <span class="font-size15 write-btn-right cur" @click="labelSave">{{ $t("save") }}</span>
                </div>
                <div class="headerSelect-alert5" style="padding: 20px 0;height: calc(100% - 96px);">
                    <p class="color999 paddingLR15">{{ $t("knowledge_share_tips") }}</p><!--可选择一个或多个标签-->
                    <ul>
                        <li v-for="(klTag, index) in getTagList" :key="klTag.tag_id" style="padding: 0">
                            <input
                                hidden
                                class="catalog"
                                type="checkbox"
                                :id="`tags${index}`"
                                :value="klTag"
                                @click="selectedTagsHandle(klTag)"
                                :checked="checkedTagCompute(klTag.tag_id)">
                            <label :for="`tags${index}`" style="padding: 0 10px;display: block;border-radius: 4px;">
                                {{ klTag.tag_title }}
                            </label>
                        </li>
                    </ul>
                </div>
                <!--暂无数据-->
                <div class="box-table" style="width:100%;height:500px;" v-if="getTagList.length === 0">
                    <div class="box-table-cell" style="text-align: center;">
                        <div class="no-data">
                            <img src="../../../static/images/no-data.png" alt=""/>
                            <p class="color999">{{ $t('no_data') }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="saving-box" v-if="uploading">
            <p>
                <van-loading type="spinner" size="24" />
            </p>
            <p>{{ $t('uploading') }}</p><!--上传中-->
        </div>
        <!--tip-->
        <van-dialog
        v-model="leaveHint"
        show-cancel-button
        :title="$t('confirm_exit_1')"
        :message="$t('confirm_exit_content_1')"
        :confirmButtonText="$t('sure')"
        :cancelButtonText="$t('cancel')"
        @confirm="$router.go(-1)"
        >
        </van-dialog>
    </div>
</template>

<script>
export default {
    name: 'EditShare',
    data() {
        return {
            shareType: '',
            kbiId: '',
            tagToggle: false,
            getClassifyList: [], //分类
            getTagList: [], //标签
            upFiles: [],
            kbi_title: '',
            kbi_desc: '',
            catalogSelected: [],
            tagsSelected: [],
            content: '',
            classificationList: [],
            catalogSelectId: [],
            labelList: [],
            uploading: false,
            leaveHint: false, //离开提示
            tempDeleteFile: [],
            msg: ''
        };
    },
    methods: {
        //退出当前页面，如果填写了信息，提示弹出层，否则直接返回上一个页面
        back() {
            if (this.$route.query.type === 'IMAGE' || this.$route.query.type === 'VEDIO' || this.$route.query.type === 'DOCUMENT' || this.$route.query.type === 'FILES') { //图片
                if (this.kbi_title === '' && this.kbi_desc === '' && this.upFiles.length === 0 && this.classificationList.length === 0 && this.labelList.length === 0) {
                    this.$router.go(-1);
                } else {
                    this.leaveHint = true;
                }
            } else { //文章
                if (this.kbi_title === '' && this.kbi_desc === '' && this.content === '' && this.upFiles.length === 0 && this.classificationList.length === 0 && this.labelList.length === 0) {
                    this.$router.go(-1);
                } else {
                    this.leaveHint = true;
                }
            }
        },
        tagSelect(toggleType) {
            this.tagToggle = true;
            switch (toggleType) {
            case 'classify':
                this.toggleType = 'classify'; //分类
                break;
            case 'tag':
                this.toggleType = 'tag'; //标签
                break;
            };
        },
        closeLayer(event) {
            this.tagToggle = false;
        },
        arrayToString(arr, key, spit) {
            let str = [];
            if (arr && arr.length > 0) {
                for (let item of arr) {
                    str.push(item[key]);
                }
            }
            return str.join(spit);
        },
        validataFile(file, uploadType) {
            if (!file || file === '' || !uploadType || uploadType === '') { return false; };
            var fileType = file.substring(file.lastIndexOf('.') + 1);
            var checkType = '';
            switch (uploadType) {
            case 'IMAGE' :
                checkType = 'jpg-jpeg-gif-png-JPG-JPEG-GIF-PNG';
                break;
            case 'DOCUMENT' :
                checkType = 'doc-docx-xls-xlsx-ppt-pptx-pdt-pdf-DOC-DOCX-XLS-XLSX-PPT-PPTX-PDT-PDF';
                break;
            case 'VEDIO' :
                checkType = 'mp4-MP4-mov-MOV';
                break;
            case 'FILES':
                checkType = `doc-docx-xls-xlsx-ppt-pptx-pdt-pdf-txt-
                DOC-DOCX-XLS-XLSX-PPT-PPTX-PDT-PDF-TXT-
                mp4-avi-flv-mov-3gp-mp3-
                MP4-AVI-FLV-MOV-3GP-MP3`;
            }
            if (checkType.indexOf(fileType) === -1) {
                //报错
                //提示出错
                switch (uploadType) {
                case 'IMAGE' :
                    this.msg = this.$t('lab_file_tips_6');
                    break;
                case 'DOCUMENT' :
                    this.msg = this.$t('lab_file_tips_11');
                    break;
                case 'VEDIO' :
                    this.msg = this.$t('lab_file_tips_12');
                    break;
                case 'FILES' :
                    this.msg = this.$t('lab_file_tips_14');
                    break;
                }
                this.$toast(this.msg);
                return false;
            }
            return true;
        },
        shareUpFile(event) { //上传文件
            if (!this.validataFile(event.target.value, this.$route.query.type)) {
                return;
            };
            this.uploading = true;
            let fromData = new FormData();
            fromData.append('file', event.target.files[0]);
            this.$axios({
                method: 'POST',
                url: '/app/kb/attachment/uploadMobile',
                headers: {'Content-Type': 'multipart/form-data'},
                data: fromData
            }).then(res => {
                this.uploading = false;
                if (this.$route.query.type === 'IMAGE') {
                    this.upFiles.push(res.data.result.attachment);
                } else {
                    this.$set(this.upFiles, 0, res.data.result.attachment);
                }
            });
        },
        deleteUpFile(index, id) {
            this.tempDeleteFile.push(id);
            this.upFiles.splice(index, 1);
            /*
            this.$axios({
                method: 'POST',
                url: `/app/kb/attachment/delete/${id}`
            }).then(res => {
                this.upFiles.splice(index, 1);
            });
            */
        },
        save() {
            let catalog = this.arrayToString(this.catalogSelected, 'kbc_id', ',');
            let tag = this.arrayToString(this.tagsSelected, 'tag_id', ',');
            let content = this.arrayToString(this.upFiles, 'kba_id', ',');
            let formData = new FormData();
            let _this = this;
            formData.append('json', JSON.stringify({
                kbi_title: this.kbi_title,
                kbi_desc: this.kbi_desc,
                kbi_content: content.length !== 0 ? content : this.content,
                kbi_type: this.$route.query.type,
                kbi_default_image: '/imglib/knowledge/h1/kc_a_01.jpg',
                kbi_online: 'OFFLINE',
                kbi_id: this.$route.query.kbiId
            }));
            this.$axios({
                method: 'POST',
                url: '/app/kb/center/mobile/insert',
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                data: formData,
                params: {
                    tag: tag,
                    catalog: catalog
                }
            }).then(res => {
                //删除已标记的文件
                for (let i = 0; i < _this.tempDeleteFile.length; i++) {
                    this.$axios({
                        method: 'POST',
                        url: `/app/kb/attachment/delete/${_this.tempDeleteFile[i]}`
                    }).then(res => {});
                }
                this.$toast(this.$t('knowledge_share_tips_5'));
                setTimeout(() => {
                    this.$router.replace({path: '/knowledge/MySharing'});
                }, 3000);
            });
        },
        classificationSave() { //分类保存
            this.tagToggle = false;
            this.classificationList = this.catalogSelected;
        },
        labelSave() {
            this.tagToggle = false;
            this.labelList = this.tagsSelected;
        },
        selectedCatalogHandle(klClassify) {
            for (let i = 0; i < this.catalogSelected.length; i++) {
                let item = this.catalogSelected[i];
                if (item.kbc_id === klClassify.kbc_id) {
                    this.catalogSelected.splice(i, 1);
                    return;
                }
            }
            this.catalogSelected.push(klClassify);
        },
        selectedTagsHandle(klTag) {
            for (let i = 0; i < this.tagsSelected.length; i++) {
                let item = this.tagsSelected[i];
                if (item.tag_id === klTag.tag_id) {
                    this.tagsSelected.splice(i, 1);
                    return;
                }
            }
            this.tagsSelected.push(klTag);
        }
    },
    mounted() {
        this.shareType = this.$route.query.type;
        this.kbiId = this.$route.query.kbiId;
        switch (this.shareType) {
        case 'IMAGE':
            this.shareType = this.$t('pictures'); //图片
            break;
        case 'VEDIO':
            this.shareType = this.$t('video'); //视频
            break;
        case 'ARTICLE':
            this.shareType = this.$t('article'); //文章
            break;
        case 'DOCUMENT':
            this.shareType = this.$t('document'); //文档
            break;
        case 'FILES':
            this.shareType = this.$t('FILES'); //文件
            break;
        };
        //分类
        this.$axios({
            method: 'POST',
            url: '/app/kb/catalog/admin/getCatalogJson'
        }).then((res) => {
            this.getClassifyList = res.data;
        });
        //标签
        this.$axios({
            method: 'POST',
            url: '/app/kb/tag/admin/getTagJson'
        }).then((res) => {
            this.getTagList = res.data;
        });
        //回显
        this.$axios({
            method: 'POST',
            url: '/app/kb/center/getKbItem',
            params: {
                kbiId: this.kbiId
            }
        }).then(res => {
            this.kbi_title = res.data.kbi_title;
            this.kbi_desc = res.data.kbi_desc;
            this.content = res.data.kbi_content;
            this.classificationList = res.data.catalogues;
            this.labelList = res.data.tags;
            this.upFiles = res.data.attachments;
            let arr = [];
            for (let item of res.data.catalogues) {
                arr.push(item.kbc_id);
                this.catalogSelectId = arr;
            }
            this.catalogSelected = this.classificationList;
            this.tagsSelected = this.labelList;
        });
    },
    filters: {
        omit(val, type) {
            if (val) {
                let nameString = val.substr(0, val.lastIndexOf('.'));
                if (nameString.length > 13) {
                    nameString = `${nameString.substr(0, 7)}...${nameString.substr(-5)}`;
                }
                return `${nameString}.${type}`;
            } else {
                return val;
            }
        }
    },
    created() {
        this.$Validator.extend('tipsTitle', {
            validate(value) {
                let num = 0;
                for (let i = 0; i < value.length; i++) {
                    if (value.charCodeAt(i) > 127 || value.charCodeAt(i) === 94) {
                        num += 2;
                    } else {
                        num += 1;
                    }
                }
                if (num > 80) {
                    return false;
                } else {
                    return true;
                }
            }
        });
        this.$Validator.extend('tipsDetail', {
            validate(value) {
                let num = 0;
                for (let i = 0; i < value.length; i++) {
                    if (value.charCodeAt(i) > 127 || value.charCodeAt(i) === 94) {
                        num += 2;
                    } else {
                        num += 1;
                    }
                }
                if (num > 400) {
                    return false;
                } else {
                    return true;
                }
            }
        });
        this.$Validator.extend('tipsContent', {
            validate(value) {
                let num = 0;
                for (let i = 0; i < value.length; i++) {
                    if (value.charCodeAt(i) > 127 || value.charCodeAt(i) === 94) {
                        num += 2;
                    } else {
                        num += 1;
                    }
                }
                if (num > 20000) {
                    return false;
                } else {
                    return true;
                }
            }
        });
    },
    computed: {
        checkedCatalogCompute() {
            return function(kbcId) {
                for (let i = 0; i < this.catalogSelected.length; i++) {
                    let item = this.catalogSelected[i];
                    if (item.kbc_id === kbcId) {
                        return true;
                    }
                }
                return false;
            };
        },
        checkedTagCompute() {
            return function(tagId) {
                for (let i = 0; i < this.tagsSelected.length; i++) {
                    let item = this.tagsSelected[i];
                    if (item.tag_id === tagId) {
                        return true;
                    }
                }
                return false;
            };
        }
    }
};
</script>

<style scoped>
    .module-list-10 li {
        height: 60px;
        line-height: 60px;
        border-bottom: 1px solid #e6e6e6;
        background: #ffffff;
        padding: 0 15px;
    }
    .module-list-10 li:nth-last-child(1) {
        border-bottom: none;
    }
    .arrow-right {
        margin: 25px 0 0 0;
    }
    .popup-box {
        position: absolute;
        top: 0;
        z-index: 101;
        width: 100%;
        height: 100%;
        padding: 0;
        background: #ffffff;
    }
    .catalog:checked + label, .catalog.cur + label {
        background: #075ebb;
        color: #ffffff;
    }
    .word-title-08 {
        float: right;
        margin-right: 5px;
        max-width: 130px;
        overflow: hidden;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
</style>
